<template>
  <n-tooltip trigger="hover">
    <template #trigger>
      <n-button
        text
        class="mr-2"
        :disabled="undoDisabled"
        @click="handleUndo()"
      >
        <template #icon>
          <n-icon size="22" class="cursor-pointer">
            <Undo />
          </n-icon>
        </template>
      </n-button>
    </template>
    {{ "撤销(Ctrl+Z)" }}
  </n-tooltip>

  <n-tooltip trigger="hover">
    <template #trigger>
      <n-button
        text
        class="mr-5"
        :disabled="redoDisabled"
        @click="handleRedo()"
      >
        <template #icon>
          <n-icon size="22" class="cursor-pointer">
            <Redo />
          </n-icon>
        </template>
      </n-button>
    </template>
    {{ "重做(Ctrl+Y)" }}
  </n-tooltip>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { NIcon, NTooltip } from "naive-ui";
import { Undo, Redo } from "@vicons/carbon";
import { useAddSignal } from "@/hooks/useSignal";

const undoDisabled = ref(true);
const redoDisabled = ref(true);

function historyChanged() {
  undoDisabled.value = window.editor.history.undos.length === 0;
  redoDisabled.value = window.editor.history.redos.length === 0;
}

onMounted(() => {
  useAddSignal("historyChanged", historyChanged);

  document.addEventListener("keydown", (event) => {
    // 检测 Ctrl + Z
    if (event.ctrlKey && event.key === "z") {
      event.preventDefault(); // 阻止默认行为（如浏览器撤销）
      handleUndo();
    }

    // 检测 Ctrl + Y
    if (event.ctrlKey && event.key === "y") {
      event.preventDefault(); // 阻止默认行为
      handleRedo();
    }
  });

  historyChanged();
});

onUnmounted(() => {
  document.removeEventListener("keydown", (event) => {
    // 检测 Ctrl + Z
    if (event.ctrlKey && event.key === "z") {
      event.preventDefault(); // 阻止默认行为（如浏览器撤销）
      handleUndo();
    }

    // 检测 Ctrl + Y
    if (event.ctrlKey && event.key === "y") {
      event.preventDefault(); // 阻止默认行为
      handleRedo();
    }
  });
});

//撤销
function handleUndo() {
  window.editor.undo();
}

//重做
function handleRedo() {
  window.editor.redo();
}
</script>

<style scoped lang="less"></style>
